package cn.xxstudy.storage

import android.Manifest
import android.app.Activity
import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment.*
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkResult = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            if (checkResult != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
                    100
                )
            }
        }

    }

    fun readPhoto(view: View) {
        val cursor = contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            MediaStore.MediaColumns.DATE_ADDED
        )

        cursor?.let {
            val list = ArrayList<Uri>()
            while (it.moveToNext()) {
                val id = it.getLong(it.getColumnIndex(MediaStore.MediaColumns._ID))
                val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
                list.add(uri)
            }
            val intent = Intent(this@MainActivity, GalleryActivity::class.java)
            intent.putExtra("images", list)
            startActivity(intent)
            it.close()
        }
    }

    fun savePhoto(view: View) {
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round_temp)
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
        val inputStream = ByteArrayInputStream(byteArrayOutputStream.toByteArray())
        saveInputStreamPhoto(inputStream, "${System.currentTimeMillis()}", "image/jpeg")
    }

    fun download(view: View) {


    }

    fun fileSelect(view: View) {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/*"
        startActivityForResult(intent, 200)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun download(fileUrl: String, fileName: String) {
        val url = URL(fileUrl)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        val inputStream = connection.inputStream
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, DIRECTORY_DOWNLOADS)
        val uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
        uri?.let {
            val os = contentResolver.openOutputStream(it)
            val bis = BufferedInputStream(inputStream)
            os?.let { o ->
                bis.copyTo(o)
            }
        }
    }

    private fun savePhotoToLocal(
        bitmap: Bitmap,
        displayName: String,
        mimeType: String,
        compressFormat: Bitmap.CompressFormat
    ) {
        //保存图片：适配
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, DIRECTORY_DCIM)
        } else {
            contentValues.put(
                MediaStore.MediaColumns.DATA,
                "${getExternalStorageDirectory().path}/$DIRECTORY_DCIM/$displayName"
            )
        }
        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        uri?.let {
            val outStream = contentResolver.openOutputStream(it)
            outStream?.let { os ->
                bitmap.compress(compressFormat, 100, os)
                os.close()
            }
        }
    }

    private fun saveInputStreamPhoto(inputStream: InputStream, displayName: String, mimeType: String) {
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, displayName)
        contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, DIRECTORY_DCIM)
        } else {
            contentValues.put(
                MediaStore.Images.ImageColumns.DATA,
                "${getExternalStorageDirectory().path}/$DIRECTORY_DCIM/$displayName"
            )
        }

        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        uri?.let { u ->
            val bis = BufferedInputStream(inputStream)
            val os = contentResolver.openOutputStream(u)
            os?.let {
                it.use { os ->
                    bis.copyTo(os)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 200) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                val uri = data.data
                if (uri.toString().contains("image")) {
                    val intent = Intent(this@MainActivity, GalleryActivity::class.java)
                    val list = ArrayList<Uri>()
                    list.add(uri!!)
                    intent.putExtra("images", list)
                    startActivity(intent)
                }
                Log.d(
                    "MainActivity",
                    "onActivityResult(MainActivity.java:168): uri=${data.data}"
                )
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //没要被授权
        if (requestCode == 100 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
                Toast.makeText(this, "您已拒绝授予权限【未勾选不再弹出】", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "您已拒绝授予权限【已勾选不再弹出】", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
